//
//  ReadBlueTool.m
//  WoChuangFu
//
//  Created by 陈贵邦 on 15/7/7.
//  Copyright (c) 2015年 asiainfo-linkage. All rights reserved.
//

#import "CardReaderManager.h"
#import <BLEIDCardReaderItem/BLEIDCardReaderItem.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "SRIDCardReader/SRIDCardReader.h"
#import "SVProgressHUD.h"
#import "ZSYPopListView.h"
#import "GDataXMLNode.h"
#import "UploadFile.h"

#define SMS_PHONE_CENTER                @"13010591500"
typedef enum {
    KEBlueToolFlag = 10,
    SRBlueToolFlag
} BoolToolTypeFlag;


@interface  CardReaderManager()<CBCentralManagerDelegate,SRIDCardReaderDelegate,BR_Callback,ZSYPopListViewDelegate>{
    BoolToolTypeFlag currentBlueToolFlag;//当前的蓝牙舍内厂商;
    BleTool *KETool;//卡尔设备
    SRIDCardReader* SRTool;//深瑞设备
    NSArray* SRDevArr; //深瑞设备列表
    SRMyPeripheral *currentSRToolPer;//当前SR连接的对象
    ZSYPopListView *zsy;
    GetCertInfoBlock srcertBlock;
    NSDictionary *usingBlueToolDic;
    ChooseBlueToolBlock choseblueblock;
    ConnectResultBlock  connectresultBlock;
    WriteCardBlock skwriteCardBlock;
    CheckCardBlock scheckCardBlock;
    
    
    BOOL tempSRconnectStat;
    
    
}
@end


@implementation CardReaderManager
static CardReaderManager *tool;
//@synthesize searchBlueToolBlock,connectToBlueToolsBlock,getCertInfoBlock,checkCardBlock,writeCardBlock;
+(CardReaderManager*)shareTool{
    
    if (tool == nil) {
        tool = [[CardReaderManager alloc]init];
    }
    
    return tool;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        KETool =[[BleTool alloc]init:self];//卡尔蓝牙初始化
        //森瑞初始化
//        SRTool =  [SRIDCardReader instanceWithManagerIP:@"121.31.60.237" port:6100 account:@"unicom_guangxi" password:@"G23#1bcz"];
        
        SRTool = [SRIDCardReader instanceWithManagerIP:@"121.31.60.237" port:6100 account:@"unicom_guangxi" password:@"G23#1bcz" key:@"99725AAD24C017318622F087BB792874"];
        SRTool.delegate = self;
        [SRTool setServerIP:@"121.31.60.237" andPort:6000];
        [tool SRtoolRefreshTools];
        currentSRToolPer = [[SRMyPeripheral alloc]init];
        
    }
    return self;
}

-(void)SRtoolRefreshTools{
    [SRTool refreshDeviceList];
}

#pragma mark - 搜索蓝牙设备
-(void)searchBlueTool:(SearchBlueToolBlock)searchBlueToolBlock ChooseBlueToolBlock:(ChooseBlueToolBlock)chooseBlueToolBlock ConnectResult:(ConnectResultBlock)connectRs{
    choseblueblock =  chooseBlueToolBlock;
    connectresultBlock = connectRs;
    [SVProgressHUD showWithStatus:@"正在搜索读卡器" maskType:SVProgressHUDMaskTypeClear];
    NSMutableArray *devarry = [[NSMutableArray alloc]init];
    NSArray *arry = [KETool ScanDeiceList:2.0f];
    [SVProgressHUD dismiss];
    [devarry addObjectsFromArray:arry];
    if (devarry && devarry != nil && devarry.count > 0) {
        NSLog(@"设备信息 %@",devarry);
        for (NSDictionary *dic in arry) {
            if ( dic.count <= 0 || [dic allKeys].count <= 0) {
                NSLog(@"移除信息 ");
                [devarry removeObject:dic];
            }
        }
        if(devarry.count <= 0){
            [SVProgressHUD dismiss];
            [self showAlertViewWithTitle:@"搜索提示" Message:@"搜索不到读卡器,请重试" Tag:0];
            
        }
        else {
            [SVProgressHUD dismiss];
            //设备索索成功
            if (searchBlueToolBlock)searchBlueToolBlock(devarry);
            [self showSelectBlueToolAlertView:devarry];
        }
    }else{
        [SVProgressHUD dismiss];
        [self showAlertViewWithTitle:@"搜索提示" Message:@"搜索不到读卡器,请重试" Tag:0];
    }
    
    
}
#pragma mark 弹出蓝牙选择框
-(void)showSelectBlueToolAlertView:(NSArray *)arry{
    zsy = [[ZSYPopListView alloc]initWitZSYPopFrame:CGRectMake(0, 0, 200, arry.count  * 55 + 50) WithNSArray:[arry copy]  WithString:@"选择蓝牙读卡器类型"];
    zsy.isTitle = NO;
    zsy.delegate = self;
}
#pragma mark 蓝牙选择框代理
-(void)sureDoneWith:(NSDictionary *)resion{
    if (zsy) {
        [zsy dissViewClose];
        zsy = nil;
        zsy.delegate = nil;
    }
    usingBlueToolDic = resion;
    if(choseblueblock)choseblueblock(resion);
    NSString *str = [[resion valueForKey:@"name"] substringToIndex:2];
    if ([str isEqualToString:@"SR"]) {
        if ([SRDevArr count] <= 0 ) {
            [SVProgressHUD dismiss];
            [SRTool refreshDeviceList];
            [self showAlertViewWithTitle:@"森锐读卡器提醒您" Message:@"搜索不到森锐读卡器\n1.请检查手机蓝牙是否打开\n2.请检查读卡器是否打开\n3.请检查是否有其他设备连接该读卡器\n3.请重新打开读卡器" Tag:0];
            return;
        }
    currentBlueToolFlag = SRBlueToolFlag;
    }else if ([str isEqualToString:@"KT"]){
        currentBlueToolFlag = KEBlueToolFlag;
    }else{
        
        [self showAlertViewWithTitle:@"提示" Message:@"您选择的蓝牙设备非读卡器,请重新选择" Tag:0];
        return;
    }
    [self connectToBlueTool:nil blueToolDic:resion];
}

-(void)connectToBlueTool:(ConnectResultBlock)connectResultBlock blueToolDic:(NSDictionary*)toolDic{
    [SVProgressHUD showWithStatus:@"正在连接读卡器" maskType:SVProgressHUDMaskTypeClear];
    if (currentBlueToolFlag == SRBlueToolFlag) {
        currentSRToolPer.advName = [toolDic valueForKey:@"name"];
        currentSRToolPer.mac = [toolDic valueForKey:@"uuid"];
        BOOL isconnectToSR = [SRTool setLisentPeripheral:currentSRToolPer];
        tempSRconnectStat = isconnectToSR;
        if (isconnectToSR) {
            [SVProgressHUD dismiss];
            [SVProgressHUD showSuccessWithStatus:@"S读卡器连接成功,请继续操作"];
        }else{
            [SVProgressHUD dismiss];
            [self showAlertViewWithTitle:@"连接提示" Message:@"S读卡器连接失败,请重试" Tag:0];
        }
        if(connectresultBlock)connectresultBlock(isconnectToSR);
    }else if (currentBlueToolFlag ==KEBlueToolFlag){
        currentBlueToolFlag = KEBlueToolFlag;
        [KETool connectBt:[toolDic valueForKey:@"uuid"]];
    }
}
-(void)getCertInfo:(GetCertInfoBlock)messageBlock isShowImage:(BOOL)isShow{
    srcertBlock = messageBlock;
    if (currentBlueToolFlag == SRBlueToolFlag) {
        //深瑞身份证信息解码
        [SVProgressHUD showWithStatus:@"正在读取身份证信息 - 森锐" maskType:SVProgressHUDMaskTypeClear];
        BOOL isconnect = [SRTool setLisentPeripheral:currentSRToolPer];
        tempSRconnectStat = isconnect;
        if(isconnect){
            
            dispatch_queue_t myCustomQueue = dispatch_queue_create("readCardid", NULL);
            dispatch_async(myCustomQueue, ^{
                [SRTool startScaleCard];
            });
            
            
            
        }else{
            [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:@"读卡器未连接" Tag:0];
        }
        
    }else if (currentBlueToolFlag == KEBlueToolFlag){
        //卡尔身份证信息解码
        [SVProgressHUD dismiss];
        [SVProgressHUD showWithStatus:@"正在读取身份证信息 - 卡尔" maskType:SVProgressHUDMaskTypeClear];
        NSMutableDictionary *certInfoDict = [[NSMutableDictionary alloc]init];
        NSDictionary *result=[KETool readIDCardS];
        NSString *resultstr = [result valueForKey:@"baseInfo"];
        if(resultstr == nil || [resultstr isEqualToString:@""]){
            [SVProgressHUD dismiss];
            [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"身份证信息读取失败\n1.请检查身份证是否放置正确\n2.请检查是否有其他设备连接该读卡器\n3.请重启读卡器" Tag:0];
            return;
            
        }else{
            
            [SVProgressHUD dismiss];
            [SVProgressHUD showSuccessWithStatus:@"身份证信息读取成功"];
            GDataXMLDocument *xmlroot=[[GDataXMLDocument alloc] initWithXMLString:resultstr options:0 error:nil];
            GDataXMLElement *xmlelement= [xmlroot rootElement];
            NSArray *xmlarray= [xmlelement children];
            NSMutableDictionary *xmldictionary=[NSMutableDictionary dictionary];
            for(GDataXMLElement *childElement in xmlarray){
                NSString *childName= [childElement name];
                NSString *childValue= [childElement stringValue];
                [xmldictionary setValue:childValue forKey:childName];
            }
            [certInfoDict setObject:[xmldictionary valueForKey:@"name"] forKey:@"name"];
            [certInfoDict setObject:[xmldictionary valueForKey:@"idNum"] forKey:@"idNum"];
            [certInfoDict setObject:[xmldictionary valueForKey:@"address"] forKey:@"address"];
            if(messageBlock)messageBlock(certInfoDict);
            
        }
        if (isShow) {
            //    相片解码 start
            NSData *_decodedImageData=[result objectForKey:@"picBitmap"];
            if(_decodedImageData!=nil){
                [SVProgressHUD showWithStatus:@"解码照片" maskType:SVProgressHUDMaskTypeClear];
                NSDictionary *imgdecodeDict=[KETool DecodePicFunc:_decodedImageData];
                NSString *errcode= [imgdecodeDict objectForKey:@"errCode"];
                NSString *errDesc= [imgdecodeDict objectForKey:@"errDesc"];
                errDesc = [NSString stringWithFormat:@"照片解码失败:%@\n1.请检查网络是否畅通\n2.如有需要请通知管理员",errDesc];
                if([errcode isEqualToString:@"-1"]){
                    
                    [SVProgressHUD dismiss];
                    
                    
                    [self showAlertViewWithTitle:@"卡尔读卡器提醒您" Message:errDesc Tag:0];
                    return;
                    
                    
                }else if([errcode isEqualToString:@"0"]){
                    [SVProgressHUD dismiss];
                    [SVProgressHUD showSuccessWithStatus:@"照片解码成功"];
                    NSData *imgdecodeData=[imgdecodeDict objectForKey:@"DecPicData"];
                    [certInfoDict setObject:imgdecodeData forKey:@"imageData"];
                    if(messageBlock)messageBlock(certInfoDict);
                }
            }else{
                return;
            }
        }
        
    }
}



/*
 10 蓝牙断开  11 检查不到数据出错  12非白卡  13 白卡  14 检查白卡失败 15入参非法 16 卡未插入 17 不识别的sim卡 18卡插入但还未初始化   19 无法发送消息wirteCharacter is nil
 
 */
-(void)checkCard:(CheckCardBlock)checkCardBlock{
    scheckCardBlock = checkCardBlock;
    if (currentBlueToolFlag == SRBlueToolFlag) {
        //深瑞写卡
        if(scheckCardBlock) scheckCardBlock(YES);
        return;
    }else if (currentBlueToolFlag == KEBlueToolFlag){
        //卡尔检查白卡
        [self KECheckCard];
        
    }else{
        [self showAlertViewWithTitle:@"提示" Message:@"未连接读卡器" Tag:0];
    }
}



-(void)KECheckCard{
    
    if (![KETool connectStatus]) {
        [SVProgressHUD dismiss];
        [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"请先连接蓝牙" Tag:0];
        return;
        
    }
    __weak typeof(KETool) weKETool = KETool;
    __weak typeof(self) weself = self;
    __block NSDictionary *checkData2G;
    __block NSDictionary *checkData3G;
    
    dispatch_queue_t queue = dispatch_queue_create("shunxun", DISPATCH_QUEUE_SERIAL);
    dispatch_sync(queue, ^{
        
        NSLog(@"队列1开");
        [SVProgressHUD showWithStatus:@"正在检查白卡" maskType:SVProgressHUDMaskTypeClear];
        checkData2G = [weKETool CheckSIMisBlank:0];
        [SVProgressHUD dismiss];
        NSLog(@"队列1结");
        
    });
    dispatch_sync(queue, ^{
        NSLog(@"队列2开");
        [SVProgressHUD showWithStatus:@"正在检查白卡" maskType:SVProgressHUDMaskTypeClear];
        checkData3G =   [weKETool CheckSIMisBlank:1];
        [SVProgressHUD dismiss];
        NSLog(@"队列2结");
        
    });
    NSString *isBlank2G =[NSString stringWithFormat:@"%@",[checkData2G objectForKey:@"isBlank"]];
    NSString *isBlank3G = [NSString stringWithFormat:@"%@",[checkData3G objectForKey:@"isBlank"]];
    NSString *checkErrorCode2G = [NSString stringWithFormat:@"%@",[checkData2G objectForKey:@"errCode"]];
    NSString *checkErrorCode3G = [NSString stringWithFormat:@"%@",[checkData3G objectForKey:@"errCode"]];
//    NSString *str = [NSString stringWithFormat:@"%@  %@  %@  %@",isBlank2G,isBlank3G,checkErrorCode2G,checkErrorCode3G];
    
    if ([checkErrorCode2G isEqualToString:@"1"]&&[checkErrorCode2G isEqualToString:@"1"]) {
        if ([isBlank3G isEqualToString:@"0"]&&[isBlank2G isEqualToString:@"0"]) {
            if(scheckCardBlock)scheckCardBlock(YES);
        }else{
            NSLog(@"卡尔检查白卡——非白卡");
            [self uploadLog];
            [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"当前卡不是白卡,请换卡重试" Tag:0];
            return ;
        }
    }else{
        
        [self showCheckError:(int)[checkErrorCode3G integerValue]];
    }
}



-(void)showCheckError:(int)errorCode{
    //    *errCode:1成功 0 失败 -2入参非法 2卡未插入 3不识别的sim卡 4卡插入但还未初始化  -4设备未连接 -5无法发送消息wirteCharacter
    NSString *errorDesc = nil;
    switch (errorCode) {
        case 0:
            errorDesc = @"检查白卡失败 ,请重试";
            break;
        case -2:
            
            errorDesc = @"检查白卡失败 ,入参非法,请联系管理员";
            break;
        case 2:
            errorDesc = @"检查白卡失败 ,卡未插入";
            break;
            
            
        case 3:
            errorDesc = @"检查白卡失败 ,白卡无法识别,请检查白卡";
            break;
        case 4:
            errorDesc = @"检查白卡失败 ,卡插入但还未初始化";
            break;
        case -4:
            errorDesc = @"检查白卡失败 ,设备未连接";
            break;
        case -5:
            errorDesc = @"检查白卡失败 ,设备无法通讯";
            break;
        default:
            break;
    }
    NSLog(@"检查白卡出错:%@",errorDesc);
    [self uploadLog];
    [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:errorDesc Tag:0];
}


/*
 10 蓝牙断开 11 失败
 
 */
-(void)readIccid:(ReadICCIDBlock)readiccidBlock{
    if (currentBlueToolFlag == SRBlueToolFlag) {
        [self performSelectorInBackground:@selector(SRReadiccid:) withObject:readiccidBlock];
    }else if (currentBlueToolFlag == KEBlueToolFlag){
        [self performSelectorInBackground:@selector(KEReadiccid:) withObject:readiccidBlock];
    }else{
        [self showAlertViewWithTitle:@"提示" Message:@"还未连接读卡器" Tag:0];
    }
}


/*
 10 连接蓝牙失败  11写卡成功  12 写imsi失败 13 写imsi入参非法 14写imsi卡未插入 15写imsi不识别的卡  16卡插入但未初始化   17 写卡超时 18 设备未连接  19 无法发送消息
 */

-(void)writeCard:(WriteCardBlock)writeCardBlock imsi:(NSString*)imsi sms:(NSString*)sms num:(NSString *)num{
    
    skwriteCardBlock = writeCardBlock;
    NSDictionary *writeDict = [NSDictionary dictionaryWithObjectsAndKeys:writeCardBlock,@"block",imsi,@"imsi",nil];
    if (currentBlueToolFlag == SRBlueToolFlag) {
        //森锐先写短信中心
        [self performSelectorInBackground:@selector(SRWriteSMS:) withObject:writeDict];
    }else if (currentBlueToolFlag == KEBlueToolFlag){
        //卡尔写卡
        [self performSelectorInBackground:@selector(KEWriteSMS:) withObject:writeDict];
    }else{
        [self showAlertViewWithTitle:@"提示" Message:@"还未连接读卡器" Tag:0];
    }
}

-(NSDictionary *)getUsingBlueToolDic{
    return usingBlueToolDic;
}

/*
 断开所有蓝牙b85e8738a09000193c82b16b3379b49305117581
 */
+(void)destroyAllTools{
    if (tool){
        [tool exitTool];
//        tool = nil;
    }
}
-(void)exitTool{
    tempSRconnectStat = NO;
//    [SRTool stopRefreshDeviceList];
////    if (KETool)KETool = nil;
////    if (SRTool)SRTool = nil;
//    if (SRDevArr)SRDevArr = nil;
//    if (currentSRToolPer)currentSRToolPer = nil;
//    if (zsy)zsy = nil;
//    if(srcertBlock)srcertBlock = nil;
//    if(usingBlueToolDic)usingBlueToolDic = nil;
//    if(choseblueblock)choseblueblock = nil;
//    if(connectresultBlock)connectresultBlock = nil;
//    if(skwriteCardBlock)skwriteCardBlock = nil;
//    if(scheckCardBlock)scheckCardBlock = nil;
}

#pragma mark - 系统蓝牙代理
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    
}
-(BOOL)currentToolConnectStat{
    if (currentBlueToolFlag == SRBlueToolFlag) {
        return tempSRconnectStat;
    }else if(currentBlueToolFlag == KEBlueToolFlag){
        return [KETool connectStatus];
    }else{
        return NO;
    }
}
#pragma mark = 卡尔代理
-(void)BR_connectResult:(BOOL)isconnected{
    if (isconnected) {
        [SVProgressHUD showSuccessWithStatus:@"卡尔读卡器连接成功,请继续操作"];
    }else{
        [SVProgressHUD showErrorWithStatus:@"卡尔读卡器连接失败,请重试"];
    }
    if(connectresultBlock)connectresultBlock(isconnected);
}

#pragma mark - 森瑞代理
- (void)didUpdatePeripheralList:(NSArray *)peripherals{
    SRDevArr = peripherals;
}
/*
 功能：代理方法，读取身份证失败时可以通过这个代理方法获取失败的蓝牙对象和原因。
 参数：peripheral 代表蓝牙设备的对象
 error 描述失败的具体原因
 返回值：无
 */
- (void)failedBack:(SRMyPeripheral*)peripheral withError:(NSError *)error{
    
    if(srcertBlock)srcertBlock(nil);
    [SVProgressHUD dismiss];
    NSString *errorStr = [NSString stringWithFormat:@"身份证信息读取失败:\n%@\n1.请检查身份证放置是否正确\n2.请检查网络是否畅通",[error localizedDescription]];
    [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:errorStr Tag:0];
}
/*
 功能： 代理方法，读取身份证成功时可以通过这个代理方法获取身份证的文本信息和照片信息。
 参数：peripheral代表蓝牙设备的对象
 data 如果data是NSDictionary类型，则里面包含的信息是文本信息，具体获取各字段信息见下表；如果data是NSData类型，则里面包含的是照片的二进制数据流
 返回值：无
 */
- (void)successBack:(SRMyPeripheral*)peripheral withData:(id)data{
    
    NSMutableDictionary *certInfoDict = [[NSMutableDictionary alloc]init];
    if([data isKindOfClass:[NSDictionary class]]){
        NSDictionary *idInfo=(NSDictionary *)data;
        [certInfoDict setObject:[idInfo objectForKey:@"Name"] forKey:@"name"];
        [certInfoDict setObject:[idInfo objectForKey:@"CardNo"] forKey:@"idNum"];
        [certInfoDict setObject:[idInfo objectForKey:@"Address"] forKey:@"address"];
        
        
    }else{
        [certInfoDict setObject:data forKey:@"imageData"];
    }
    if ([certInfoDict count]>0) {
        if(srcertBlock) srcertBlock(certInfoDict);
        [SVProgressHUD dismiss];
        [SVProgressHUD showSuccessWithStatus:@"身份证信息读取成功 - 森锐"];
        
    }else{
        if(srcertBlock)srcertBlock(certInfoDict);
        [SVProgressHUD dismiss];
        [SVProgressHUD showSuccessWithStatus:@"身份证信息读取失败 - 森锐,请重试"];
    }
    
    
}

#pragma mark - Alert弹窗
-(void)showAlertViewWithTitle:(NSString*)title Message:(NSString*)message Tag:(int)tag{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    
}

#pragma mark 森锐读iccid 并判断白卡
-(void)SRReadiccid:(ReadICCIDBlock)readiccidBlock{
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresshow:) withObject:@"正在读取sim卡信息 - 森锐" waitUntilDone:NO];
    BOOL isConnectToSR  =   [SRTool setLisentPeripheral:currentSRToolPer];
    tempSRconnectStat = isConnectToSR;
    if (!isConnectToSR) {
        NSLog(@"沈睿检查白卡——沈睿读卡器连不上");
        [self uploadLog];
        [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在读取sim卡信息 - 森锐" waitUntilDone:NO];
        [self showAlertViewWithTitle:@"森锐读卡器提醒您" Message:@"您的读卡器连接不上,请做如下操作:\n1.检查手机蓝牙读卡器是否打开\n2.检查读卡器是否打开\n3.重启读卡器" Tag:0];
        return;
    }
    SRIDReadCardInfo *iccidinfo  = [SRTool readCardInfo:@""];
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在读取sim卡信息 - 森锐" waitUntilDone:NO];
    NSLog(@"森锐读卡器: iccid is : %@",iccidinfo.ICCID);
    //0白卡  1非白卡
    NSLog(@"森锐白卡类型 %@",iccidinfo.CARDTYPE);
    if ([iccidinfo.CARDTYPE isEqualToString:@"1"]) {
        NSLog(@"沈睿检查白卡——非白卡");
        [self uploadLog];
        [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在读取sim卡信息 - 森锐" waitUntilDone:NO];
        [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:@"当前卡不是白卡,请换卡重试" Tag:0];
        return;
    }
    
    if (iccidinfo.ICCID == nil || [iccidinfo.ICCID isEqualToString:@""] || [iccidinfo.ICCID length] == 0) {
        NSLog(@"沈睿SIM卡iccid信息读取失败");
        [self uploadLog];
        [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在读取sim卡信息 - 森锐" waitUntilDone:NO];
        [self showAlertViewWithTitle:@"森锐读卡器提醒您" Message:@"SIM卡iccid信息读取失败\n1.请重新拔插白卡\n2.请检查读卡器状态是否正常\n3.请重新打开读卡器" Tag:0];
        return;
    }else{
        [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在读取sim卡信息 - 森锐" waitUntilDone:NO];
        if(readiccidBlock&&iccidinfo.ICCID)readiccidBlock(iccidinfo.ICCID);
        return;
    }
}

#pragma mark 卡尔读iccid
-(void)KEReadiccid:(ReadICCIDBlock)readiccidBlock{
    
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresshow:) withObject:@"正在读取sim卡信息 - 卡尔" waitUntilDone:NO];
    
    BOOL isConnectToKE  =   [KETool connectStatus];
    if (!isConnectToKE) {
        NSLog(@"卡尔读卡器提醒您您的读卡器读取sim卡信息时息时连接不上,");
        [self uploadLog];
        [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"卡尔" waitUntilDone:NO];
        [self showAlertViewWithTitle:@"卡尔读卡器提醒您" Message:@"您的读卡器读取sim卡信息时连接不上,请做如下操作:\n1.检查手机蓝牙读卡器是否打开\n2.检查读卡器是否打开\n3.重启读卡器" Tag:0];
        return;
    }
    
    
    NSDictionary *iccidDict= [KETool KaiKa];
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"卡尔" waitUntilDone:NO];
    // errCode:0 成功，-1 失败 -4设备未连接 -5无法发送消息wirteCharacter is nil
    NSString *errcode= [iccidDict objectForKey:@"errCode"];
    NSString *errDesc= [iccidDict objectForKey:@"errDesc"];
    
    if ([errcode isEqualToString:@"0"]) {
        //成功
        NSMutableString *iccidString = [[NSMutableString alloc] initWithCapacity:0];
        NSData *kaikaData=[iccidDict objectForKey:@"kaikaData"];
        NSString *kaikastr=[[NSString alloc] initWithData:kaikaData encoding:NSUTF8StringEncoding];
        [iccidString appendString:kaikastr];
        NSString *iccid = [NSString stringWithFormat:@"%@",iccidString];
        if(readiccidBlock)readiccidBlock(iccid);
        return;
    }else if ([errcode isEqualToString:@"-1"]){
        [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:errDesc Tag:0];
        NSLog(@"卡尔读卡器提醒读卡器读取sim卡信息时连接出错上,");
        [self uploadLog];
        return;
    }else if ([errcode isEqualToString:@"-4"]){
        NSLog(@"卡尔读卡器提醒读卡器读取sim卡信息时连接出错上,");
        [self uploadLog];
        [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"读卡器读取sim卡信息时连接出错\n1.请检查手机蓝牙状态\n2.请检查读卡器状态" Tag:0];
        return;
    }else if ([errcode isEqualToString:@"-5"]){
        NSLog(@"尔读卡器读取sim卡信息时通讯失败\n1.请检查手机,");
        [self uploadLog];
        [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"读卡器读取sim卡信息时通讯失败\n1.请检查手机蓝牙状态\n2.请检查读卡器状态\n3.请重新打开蓝牙并重启读卡器" Tag:0];
        return;
    }else{
        NSLog(@"尔读读取sim卡信息时发生未知错误,请重试,");
        [self uploadLog];
        [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"读取sim卡信息时发生未知错误,请重试" Tag:0];
        return;
    }
}

#pragma mark - 森锐写短信中心
/*	1:成功 0:失败 2:卡未插入3:不识别的SIM卡4:卡插入但未初始化-3:超时-4:设备未连接-5:无法发送信息*/
-(void)SRWriteSMS:(NSDictionary*)dict{
    BOOL isCo =  [SRTool setLisentPeripheral:currentSRToolPer];

    tempSRconnectStat = isCo;
    if (!isCo) {
        
        [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:@"尚未连接读卡器请重试" Tag:0];
        return;
    }
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresshow:) withObject:@"正在写短信中心 - 森锐" waitUntilDone:NO];
    int  SRWriteSMScode = [SRTool writeMSGNumber:SMS_PHONE_CENTER number:0x01];
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在写短信中心 - 森锐" waitUntilDone:NO];
    if (SRWriteSMScode == 1) {
        //写短信中心成功写imsi
        [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismissWithMessageSuccese:) withObject:@"写短信中心成功 - 森锐" waitUntilDone:NO];
        [self SRWriteIMSI:dict];
        
    }else{
        [self showWriteSMSErrorAlert:SRWriteSMScode];
    }
    
}
#pragma mark - 森锐写短信中心成功后 - 写IMSI
/*	1:成功 0:失败 2:卡未插入3:不识别的SIM卡4:卡插入但未初始化-3:超时-4:设备未连接-5:无法发送信息*/
-(void)SRWriteIMSI:(NSDictionary*)dict{
    NSString *imsi = [dict objectForKey:@"imsi"];
    if ([imsi isEqualToString:@""]||imsi ==nil) {
        [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:@"imsi尚未获取,请重试" Tag:0];
        return;
    }
    BOOL isCo =  [SRTool setLisentPeripheral:currentSRToolPer];
    tempSRconnectStat = isCo;
    if (!isCo) {
        [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:@"尚未连接读卡器请重试" Tag:0];
        return;
    }
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresshow:) withObject:@"正在写IMSI - 森锐" waitUntilDone:NO];
    int  SRWriteIMSIcode = [SRTool writeIMSI:imsi];
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在写IMSI - 森锐" waitUntilDone:NO];
    if (SRWriteIMSIcode == 1) {
        //写imsi成功
        if (skwriteCardBlock) {
            skwriteCardBlock(1);
        }
        
    }else{
        [self showWriteIMSIErrorAlert:SRWriteIMSIcode];
    }
    
}

#pragma mark - 卡尔写短信中心
/*	1:成功 0:失败 2:卡未插入3:不识别的SIM卡4:卡插入但未初始化-3:超时-4:设备未连接-5:无法发送信息*/
-(void)KEWriteSMS:(NSDictionary*)dict{
    NSString *imsi = [dict objectForKey:@"imsi"];
    if ([imsi isEqualToString:@""]||imsi ==nil) {
        [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:@"imsi尚未获取,请重试" Tag:0];
        return;
    }
    if(![KETool connectStatus]){
        //        [self showAlertViewWithTitle:@"提示" message:@"请先连接读卡器"];
        [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"写卡前与读卡器断开连接\n1.请检查手机蓝牙状态是否良好\n2.请检查读卡器是否打开\n3.请重启读卡器并重新打开手机蓝牙" Tag:0];
        return;
    }
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresshow:) withObject:@"正在写IMSI - 卡尔" waitUntilDone:NO];
    int  KEWriteMSMcode = [KETool WriteMsgCenter:SMS_PHONE_CENTER withNumberIndex:(Byte)0x01];
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在写IMSI - 卡尔" waitUntilDone:NO];
    
    if (KEWriteMSMcode == 1) {
        //写imsi
        [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismissWithMessageSuccese:) withObject:@"写短信中心成功 - 卡尔" waitUntilDone:NO];
        [self KEWriteIMSI:dict];
        
    }else{
        [self showWriteSMSErrorAlert:KEWriteMSMcode];
    }
}
#pragma mark - 卡尔写短信中心成功后 - 写IMSI
/*	1:成功 0:失败 2:卡未插入3:不识别的SIM卡4:卡插入但未初始化-3:超时-4:设备未连接-5:无法发送信息*/
-(void)KEWriteIMSI:(NSDictionary*)dict{
    NSString *imsi       = [dict objectForKey:@"imsi"];
    
    if ([imsi isEqualToString:@""]||imsi ==nil) {
        [self showAlertViewWithTitle:@"森锐读卡器提示您" Message:@"imsi尚未获取,请重试" Tag:0];
        return;
    }
    NSData *imsi2g       = [imsi dataUsingEncoding:NSUTF8StringEncoding];
    if(![KETool connectStatus]){
        //        [self showAlertViewWithTitle:@"提示" message:@"请先连接读卡器"];
        [self showAlertViewWithTitle:@"卡尔读卡器提示您" Message:@"写卡前与读卡器断开连接\n1.请检查手机蓝牙状态是否良好\n2.请检查读卡器是否打开\n3.请重启读卡器并重新打开手机蓝牙" Tag:0];
        return;
    }
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresshow:) withObject:@"正在写IMSI - 卡尔" waitUntilDone:NO];
    int  SRWriteIMSIcode = [KETool WriteSIMCardwithIMSI1:imsi2g andIMSI2:imsi2g];
    [self performSelectorOnMainThread:@selector(mainThreadSVProgresdismiss) withObject:@"正在写IMSI - 卡尔" waitUntilDone:NO];
    if (SRWriteIMSIcode == 1) {
        //写imsi
        if(skwriteCardBlock)skwriteCardBlock(1);
    }else{
        [self showWriteIMSIErrorAlert:SRWriteIMSIcode];
    }
    
}
-(void)mainThreadSVProgresshow:(NSString *)message{
    [SVProgressHUD showWithStatus:message maskType:SVProgressHUDMaskTypeClear];
}
-(void)mainThreadSVProgresdismiss{
    [SVProgressHUD dismiss];
}
-(void)mainThreadSVProgresdismissWithMessageSuccese:(NSString *)message{
    [SVProgressHUD showSuccessWithStatus:message];
}

-(void)mainThreadSVProgresdismissWithMessageError:(NSString *)message{
    [SVProgressHUD showErrorWithStatus:message];
}
-(void)showWriteSMSErrorAlert:(NSInteger )errorcode{
    NSString *desc = nil;
    NSString *title = nil;
    if (currentBlueToolFlag == SRBlueToolFlag) {
        title = @"森锐读卡器提示您";
    }else if(currentBlueToolFlag == KEBlueToolFlag){
        title = @"卡尔读卡器提示您";
    }else{
        title = @"未知读卡器提示";
    }
    switch (errorcode) {
        case 1:
            desc = @"写短信中心成功";
            break;
        case 0:
            desc = @"写短信中心失败";
            
            break;
        case 2:
            desc = @"白卡卡未插入,请检查白卡或重新拔插白卡";
            break;
        case 3:
            desc = @"不识别的白卡,请检查";
            break;
        case 4:
            desc = @"卡插入但未初始化";
            break;
        case -3:
            desc = @"写短信中心超时,请重试";
            break;
        case -4:
            desc = @"未连接读卡器\n1.请检查手机蓝牙是否打开\n2.请检查读卡器是否打开\n3.请检查是否有其他手机连接该设备\n4.请重新打开蓝牙和读卡器";
            break;
        case -5:
            desc = @"读卡器无法通讯";
            break;
            
        default:
            break;
    }
    NSLog(@"写短信中心失,%@",desc);
    [self uploadLog];
    [self showAlertViewWithTitle:title Message:desc Tag:0];
}

-(void)showWriteIMSIErrorAlert:(NSInteger )errorcode{
    NSString *desc = nil;
    NSString *title = nil;
    if (currentBlueToolFlag == SRBlueToolFlag) {
        title = @"森锐读卡器提示您";
    }else if(currentBlueToolFlag == KEBlueToolFlag){
        title = @"卡尔读卡器提示您";
    }else{
        title = @"未知读卡器提示";
    }
    switch (errorcode) {
        case 1:
            desc = @"写IMSI成功";
            break;
        case 0:
            desc = @"写IMSI失败";
            if(skwriteCardBlock)skwriteCardBlock(99);
            break;
        case 2:
            desc = @"白卡卡未插入,请检查白卡或重新拔插白卡";
            break;
        case 3:
            desc = @"不识别的白卡,请检查";
            break;
        case 4:
            desc = @"卡插入但未初始化";
            break;
        case -3:
            desc = @"写IMSI超时,请重试";
            if(skwriteCardBlock)skwriteCardBlock(88);
            break;
        case -4:
            desc = @"未连接读卡器\n1.请检查手机蓝牙是否打开\n2.请检查读卡器是否打开\n3.请检查是否有其他手机连接该设备\n4.请重新打开蓝牙和读卡器";
            break;
        case -5:
            desc = @"读卡器无法通讯";
            break;
            
        default:
            break;
    }
    NSLog(@"写IMSI,%@",desc);
    [self uploadLog];
    [self showAlertViewWithTitle:title Message:desc Tag:0];
}

-(void)testSRwriteMSM{
    [self performSelectorInBackground:@selector(SRWriteSMS:) withObject:@"460017027621731"];
}
-(void)insertSMS{
    BOOL isCo =  [SRTool setLisentPeripheral:currentSRToolPer];
    tempSRconnectStat = isCo;
    if (!isCo) {
        [self showAlertViewWithTitle:@"读卡器没连接" Message:@"" Tag:0];
        return;
    }
    int  writeSMSresult = [SRTool writeMSGNumber:SMS_PHONE_CENTER number:0x01];;
    
    NSString *tr = [NSString stringWithFormat:@"结果 :%d",writeSMSresult];
    [self showAlertViewWithTitle:@"SR写短信" Message:tr Tag:0];
}




-(void)uploadLog{
    NSThread* myThread = [[NSThread alloc] initWithTarget:self
                                                 selector:@selector(realUP)
                                                   object:nil];
    [myThread start];
}
-(void)realUP{
    UploadFile *upload = [[UploadFile alloc] init];
    NSString *urlString = @"http://sjttsj.com/nocheckurl/logurl/";
    NSString *path = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents/dr.log"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSString *resultstr= [upload uploadFileWithURL:[NSURL URLWithString:urlString] data:data];
    //    [self ShowProgressHUDwithMessage:[NSString stringWithFormat:@"LOG上传:%@",resultstr]];
}





@end
